package sample.controller.todo;

import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;

public class DoneController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(DoneController.class.getName());

    @Override
    public Navigation run() {

        String key = key();
        if (!StringUtil.isEmpty(key)) {
            DatastoreService datastoreService =
                DatastoreServiceFactory.getDatastoreService();
            
            Transaction transaction = datastoreService.beginTransaction();
            try {
                Entity todo = datastoreService.get(KeyFactory.stringToKey(key));
                Boolean done = (Boolean) todo.getProperty("done");
                if (done == null || !done) {
                    done = false;
                }
                done = !done;
                todo.setProperty("done", done);
                datastoreService.put(todo);
                transaction.commit();
            } catch (EntityNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
            }
        }
        return redirect(basePath);
    }
}
